<template>
  <div>
    <van-cell v-for="(item,index) in suggestionData" :key="index" icon="search"
              @click="$emit('clickSuggestionItem',item)">
      <template #title>
        <div v-html="formatStr(item)"></div>
      </template>
    </van-cell>
    <!-- 搜索提示 -->
    <van-empty v-if="isShowEmpty" image="search" description="暂无搜索"/>
  </div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search'
import { Toast } from 'vant'

export default {
  name: 'Search-suggestion',
  data () {
    return {
      suggestionData: null, // 联想建议
      isShowEmpty: false
    }
  },
  props: {
    // 输入框的值
    searchText: {
      type: String,
      required: true
    }
  },
  watch: {
    // 监视父组件的值发生变化
    searchText: {
      immediate: true, // 开启首次监听
      handler (newVal) {
        // 防抖
        this.timer && clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          this.loadSearchSuggestion(newVal)
        }, 700)
      }
    }
  },
  methods: {
    // 获取搜索建议
    async loadSearchSuggestion (val) {
      try {
        const { options: res } = await getSearchSuggestion(val)
        // 空提示
        this.isShowEmpty = !res.length
        this.suggestionData = res
      } catch (e) {
        Toast.fail('网络异常')
      }
    },
    formatStr (item) {
      // "(>|^)([^<]*)(" + content + ")([^>]*<)","gm")
      // const reg = new RegExp(this.searchText.toString(), 'gmi')
      const reg = /\+\+/
      if (reg.test(this.searchText)) {
        return item.replace(this.searchText, '<span style="color:red">' + this.searchText + '</span>')
      }
      const reg2 = new RegExp(this.searchText, 'gi')
      return item.replace(reg2, '<span style="color:red">' + this.searchText + '</span>')
    }
  },
  beforeDestroy () {
    clearTimeout(this.timer)
  }
}
</script>

<style scoped lang='less'>

</style>
